package org.grow.present.controller.purchase;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.grow.present.dto.MaterialQueryCondition;
import org.grow.present.entity.Material;
import org.grow.present.entity.PageResults;
import org.grow.present.exception.MissTargetException;
import org.grow.present.mapper.MaterialMapper;
import org.grow.present.service.CodeGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: xwg
 * @CreateDate: 2024/6/6
 */

@Slf4j
@RestController
@RequestMapping("/material")
public class MaterialController {
    @Autowired
    private CodeGenerator codeGenerator;

    @Autowired
    private MaterialMapper mapper;

    @PostMapping("/insert")
    public Material insert(@RequestBody Material material){
        String code = codeGenerator.nextCode("MT");
        material.setMaterialCode(code);
        int i = mapper.insert(material);
        if (i != 1){
            throw new MissTargetException("insert failed");
        }
        return material;
    }
    public Material modifyById(@RequestBody Material material){
        Material db = mapper.selectById(material.getMaterialCode());
        if(db == null){
            throw new MissTargetException("待查看的数据不存在");
        }
        db.setMaterialLable(material.getMaterialLable());
        db.setSuggestPrice(material.getSuggestPrice());
        db.setMaterialType(material.getMaterialType());
//
//        BeanUtils.copyProperties(db, material);
        int i = mapper.updateById(db);
        return db;
    }
    @GetMapping("/find/{id}")
    public Material findById(@PathVariable String id){
        Material material = mapper.selectById(id);
        if (material == null){
            throw new MissTargetException("待查看的数据不存在");
        }
        return material;
    }
    @DeleteMapping("/remove/{id}")
    public String removeById(@PathVariable String id){
        int i = mapper.deleteById(id);
        if(i != 1){
            throw new MissTargetException("remove failed");
        }
        return id;
    }
    @PostMapping("/query")
    public PageResults<Material> query(@RequestBody MaterialQueryCondition qc){
        Page<Material> page = Page.of(qc.getPageNum(), qc.getPageSize());
        System.out.println(qc);
        Page<Material> pagef= mapper.dynamicQuery(page, qc);
        return  PageResults.createByIPage(pagef);
    }
}
